package com.pvdnc.tapkit.utils;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;

import com.pvdnc.nsocket.log.SLog;
import com.pvdnc.tapkit.utils.LocalBroadcast;

import java.util.concurrent.atomic.AtomicBoolean;

public abstract class BaseLocalReceiver extends BroadcastReceiver {
    private static final SLog LOG=new SLog(BaseLocalReceiver.class);

    private String mAction;

    public BaseLocalReceiver(String action){
        mAction=action;
    }

    public static void broadcastActionOnly(String action){
        Intent intent=new Intent();
        intent.setAction(action);
        LocalBroadcast.getInstance().send(intent);
    }

    private final AtomicBoolean mRegistered=new AtomicBoolean();

    public void register(){
        if(mRegistered.get()) {
            LOG.e("receiver has been registered already");
            return;
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(mAction);
        LocalBroadcast.getInstance().register(this,filter);
        mRegistered.compareAndSet(false,true);
    }

    public void unregister(){
        LocalBroadcast.getInstance().unregister(this);
        if(!mRegistered.compareAndSet(true,false)){
            LOG.e("fail to unregister receiver (invalid status)");
        }
    }
}
